<template>
  <div>
    <el-row :gutter="15">
      <el-form ref="elForm" :model="dataForm" :rules="dataRule" size="small" label-width="100px" label-position="right"
               :disabled="setting.readonly">
        <template v-if="!loading && formOperates">
          <el-col :span="8" v-if="judgeShow('F_CreatorUserId')">
            <el-form-item label="创建用户"
                          prop="F_CreatorUserId">
              <jnpf-open-data v-model="dataForm.F_CreatorUserId"
                              readonly :disabled="judgeWrite('F_CreatorUserId')" type="currUser">

              </jnpf-open-data>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="judgeShow('F_CreatorTime')">
            <el-form-item label="创建时间"
                          prop="F_CreatorTime">
              <jnpf-open-data v-model="dataForm.F_CreatorTime"
                              readonly :disabled="judgeWrite('F_CreatorTime')" type="currTime">

              </jnpf-open-data>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="judgeShow('F_Description')">
            <el-form-item label="申请原因"
                          prop="F_Description">
              <el-input v-model="dataForm.F_Description"
                        placeholder="请输入" :maxlength="100" :disabled="judgeWrite('F_Description')" clearable
                        :style='{"width":"100%"}'>

              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('test002List') && formOperates">
            <el-form-item label-width="0">
              <div class="JNPF-common-title">
                <h2></h2>
              </div>
              <el-table :data="dataForm.test002List" size='mini'>
                <el-table-column type="index" width="50" label="序号" align="center"/>
                <el-table-column prop="F_VipLvId" label="vip等级" v-if="judgeShow('test002List-F_VipLvId')">
                  <template slot="header" v-if="judgeRequired('test002List-F_VipLvId')">
                    <span class="required-sign">*</span>vip等级
                  </template>
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.F_VipLvId"
                               placeholder="请选择"
                               :disabled="judgeWrite('test002List') || judgeWrite('test002List-F_VipLvId')" clearable
                               :style='{"width":"100%"}'>
                      <el-option v-for="(item, index) in F_VipLvIdOptions" :key="index" :label="item.fullName"
                                 :value="item.enCode" :disabled="item.disabled"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="F_expTime" label="到期时间" v-if="judgeShow('test002List-F_expTime')">
                  <template slot="header" v-if="judgeRequired('test002List-F_expTime')">
                    <span class="required-sign">*</span>到期时间
                  </template>
                  <template slot-scope="scope">
                    <el-date-picker v-model="scope.row.F_expTime"
                                    placeholder="请选择"
                                    :disabled="judgeWrite('test002List') || judgeWrite('test002List-F_expTime')"
                                    clearable :style='{"width":"100%"}' type="datetime" format="yyyy-MM-dd HH:mm:ss"
                                    value-format="timestamp">
                    </el-date-picker>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="50" v-if="!setting.readonly && !judgeWrite('test002List')">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" class="JNPF-table-delBtn" @click="deltest002List(scope.$index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="table-actions" @click="addtest002List()">
                <el-button type="text" icon="el-icon-plus">添加</el-button>
              </div>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit"/>
  </div>
</template>
<script>
import request from '@/utils/request'
import {getDataInterfaceRes} from '@/api/systemData/dataInterface'
import {getDictionaryDataSelector} from '@/api/systemData/dictionary'

export default {
  components: {},
  props: [],
  data() {
    return {
      visible: false,
      loading: false,
      setting: {},
      eventType: '',
      userBoxVisible: false,
      currTableConf: {},
      addTableConf: {
        test002List: {
          "popupType": "dialog",
          "hasPage": true,
          "popupTitle": "选择数据",
          "pageSize": 20,
          "columnOptions": [],
          "interfaceId": "",
          "interfaceName": "",
          "relationOptions": [],
          "templateJson": [],
          "popupWidth": "800px"
        },
      },
      tableRows: {
        test002List: {
          F_expTime: '',
          enabledmark: undefined
        }
      },
      dataForm: {
        id: '',
        flowId: '',
        status: 1,
        freeapproveruserid: '',
        flowUrgent: 1,
        F_CreatorUserId: undefined,
        F_CreatorTime: undefined,
        F_Description: undefined,
        test002List: [],
      },
      tableRequiredData: {},
      dataRule:
        {
          F_Description: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
            {
              pattern: /^(([1-9]\d+)|([2-9]))$/,
              message: '请输入大于1的整数',
              trigger: 'blur'
            },
          ],


        },

      F_VipLvIdOptions: [],
    }
  },
  computed: {
    formOperates() {
      return this.setting.formOperates
    }
  },
  watch: {},
  created() {
    this.getF_VipLvIdOptions();
  },
  mounted() {
  },
  methods: {
    judgeShow(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return true
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return item.read
    },
    judgeWrite(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return false
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return !item.write
    },
    getF_VipLvIdOptions() {
      getDictionaryDataSelector('366232797372744005').then(res => {
        this.F_VipLvIdOptions = res.data.list
      })
    },
    goBack() {
      this.$emit('refresh')
    },
    init(data) {
      this.dataForm.id = data.id || "";
      this.setting = data;
      this.visible = true;
      this.updateDataRule()
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields();
        if (this.dataForm.id) {
          this.loading = true
          request({
            url: '/api/example/Test001/' + this.dataForm.id,
            method: 'get'
          }).then(res => {
            this.dataInfo(res.data)
            this.loading = false
          })
        }
        this.$emit('setPageLoad')
      })
      this.$store.commit('generator/UPDATE_RELATION_DATA', {})
    },
    updateDataRule() {
      let newRules = {}
      for (let i = 0; i < this.setting.formOperates.length; i++) {
        const item = this.setting.formOperates[i]
        if (!item.id.includes('-')) {
          const newRulesItem = {
            required: item.required,
            message: item.name + '不能为空',
            trigger: item.trigger || 'blur'
          }
          if (!this.dataRule.hasOwnProperty(item.id)) {
            if (item.required) this.$set(newRules, item.id, [newRulesItem])
          } else {
            let withoutRequiredItem = true
            for (let i = 0; i < this.dataRule[item.id].length; i++) {
              if (this.dataRule[item.id][i].hasOwnProperty('required')) {
                this.dataRule[item.id][i].required = item.required
                withoutRequiredItem = false
              }
            }
            if (withoutRequiredItem && item.required) this.dataRule[item.id].push(newRulesItem)
          }
        } else {
          let key = item.id.split('-')[0]
          let newId = item.id.split('-')[1]
          let newItem = {
            ...item,
            id: newId
          }
          if (!this.tableRequiredData.hasOwnProperty(key)) {
            this.$set(this.tableRequiredData, key, [newItem])
          } else {
            this.tableRequiredData[key].push(newItem)
          }
        }
      }
      this.dataRule = {...this.dataRule, ...newRules}
    },
    exist() {
      let isOk = true
      for (let key in this.tableRequiredData) {
        if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
          for (let i = 0; i < this.dataForm[key].length; i++) {
            let item = this.dataForm[key][i]
            inner: for (let id in item) {
              let arr = this.tableRequiredData[key].filter(o => o.id === id) || []
              if (!arr.length) continue inner
              if (arr[0].required) {
                let msg = `${arr[0].name}不能为空`
                let boo = true
                if (arr[0].dataType === 'array') {
                  boo = !this.jnpf.isEmptyArray(item[id])
                } else {
                  boo = !this.jnpf.isEmpty(item[id])
                }
                if (!boo) {
                  this.$message({
                    message: msg,
                    type: 'error',
                    duration: 1000
                  })
                  isOk = false
                  break
                }
              }
            }
          }
        }
      }
      return isOk
    },
    judgeRequired(id) {
      if (!this.formOperates || !this.formOperates.length) return false
      let arr = this.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return false
      let item = arr[0]
      return item.required
    },
    // 表单提交
    dataFormSubmit(eventType, flowUrgent) {
      this.$refs['elForm'].validate((valid) => {
        if (valid) {
          if (this.exist && !this.exist()) return
          if (eventType === 'audit' || eventType === 'reject') {
            this.$emit('eventReceiver', this.dataForm, eventType)
            return
          }
          this.dataForm.status = eventType === 'submit' ? 0 : 1
          this.dataForm.flowId = this.setting.flowId
          this.dataForm.flowUrgent = flowUrgent
          this.eventType = eventType
          if (this.eventType === 'submit') {
            this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
              type: 'warning'
            }).then(() => {
              this.request()
            }).catch(() => {
            });
          } else {
            this.request()
          }
        }
      })
    },
    request() {
      var _data = this.dataList()
      if (!this.dataForm.id) {
        request({
          url: '/api/example/Test001',
          method: 'post',
          data: _data
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('close', true)
            }
          })
        })
      } else {
        request({
          url: '/api/example/Test001/' + this.dataForm.id,
          method: 'PUT',
          data: _data
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('close', true)
            }
          })
        })
      }
    },
    addtest002List() {
      let item = {
        F_VipLvId: undefined,
        F_expTime: undefined,
      }
      this.dataForm.test002List.push(item)
    },
    deltest002List(index) {
      this.dataForm.test002List.splice(index, 1);
    },
    openSelectDialog(key) {
      this.currTableConf = this.addTableConf[key]
      this.currVmodel = key
      this.selectDialogVisible = true
      this.$nextTick(() => {
        this.$refs.selectDialog.init()
      })
    },
    addForSelect(data) {
      for (let i = 0; i < data.length; i++) {
        let item = {...this.tableRows[this.currVmodel], ...data[i]}
        this.dataForm[this.currVmodel].push(item)
      }
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));


      for (let i = 0; i < _data.test002List.length; i++) {
        var _list = _data.test002List[i];
      }
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll
      for (let i = 0; i < _dataAll.test002List.length; i++) {
        var _list = _dataAll.test002List[i];
      }
      this.dataForm = _dataAll
    },
  },
}

</script>
